package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.entity.UserInfo;

public class UserDaoImpl extends BaseDao implements IUserDao {
	private Connection conn=null;
	private PreparedStatement ps=null;
	private ResultSet rs=null;
	@Override
	public int addUserInfo(UserInfo us) {
		String sql="insert into userinfo (uname,pwd,sex,email,phone) values (?,?,?,?,?)";
		Object[] obj={us.getUname(),us.getPwd(),us.getSex(),us.getEmail(),us.getPhone()};
		return this.exeUpdate(sql, obj);
	}

	@Override
	public UserInfo getUserInfo(String account, String pwd) {
		UserInfo us=null;
		String sql="select * from userinfo where (uname=? or phone=?) and pwd=?";
		conn=this.getConnection();
		try {
			ps=conn.prepareStatement(sql);
			ps.setString(1, account);
			ps.setString(2, account);
			ps.setString(3, pwd);
			rs=ps.executeQuery();
			if(rs.next()){
				us=new UserInfo();
				us.setId(rs.getInt(1));
				us.setUname(rs.getString(2));
				us.setPwd(rs.getString(3));
				us.setSex(rs.getString(4));
				us.setEmail(rs.getString(5));
				us.setPhone(rs.getString(6));
				us.setIsadmin(rs.getInt(7));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			this.closeAll(rs, ps, conn);
		}
		return us;
	}

	@Override
	public String isHaveInfo(String uname, String phone, String email) {
		// TODO Auto-generated method stub
		String sql="select * from userinfo where uname=? or phone=? or email=?";
		conn=this.getConnection();
		try {
			ps=conn.prepareStatement(sql);
			ps.setString(1, uname);
			ps.setString(2, phone);
			ps.setString(3, email);
			rs=ps.executeQuery();
			if(rs.next()){
				if(rs.getString("uname").equals(uname)){
					return uname;
				}else if(rs.getString("phone").equals(phone)){
					return phone;
				}else{
					return email;
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			this.closeAll(rs, ps, conn);
		}
		return "";
	}
}
